package bbs.mvc.Servlet;

import bbs.mvc.Filter.AuthFilter;
import bbs.mvc.Beans.DBUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "loginServlet", value = "/login-servlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1198763434511986380L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        String user = request.getParameter("username");
        String pass = request.getParameter("password");
        String code = request.getParameter("code");
        String sql;
        int init_page =1;
        //根据用户名从数据库中取出密码
        HttpSession session = request.getSession(true);
        session.setAttribute("page",init_page);
        String validateCode = (String)session.getAttribute(IdenterfyServlet.uri);
        String password = null;
        try {
            password = DBUtils.getUser(user).getPassword();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if(!(validateCode.equals(code))){
            System.out.println("验证码内容错误 应当: "+session.getAttribute(IdenterfyServlet.uri));
            System.out.println("实际输入: "+session.getAttribute(code));
            response.sendRedirect("/BBS_war_exploded/");
        }
        else if (user != null && pass != null) {
            if (pass.equals(password)) {

                session.setAttribute(AuthFilter.LOGIN_STATUS, Boolean.TRUE);
                session.setAttribute("user",user);
                response.sendRedirect("./admin/Arstartes.jsp");
            } else {
                response.sendRedirect("/BBS_war_exploded/");
            }
        }
    }
}

